package com.dfec.water.util;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author trg
 * @description: TODO
 * @title: GreenPixelCalculator
 * @projectName water-soil-conservation-serve
 * @email 1446232546@qq.com
 * @date 2025/2/25 9:52
 */
public class GreenPixelCalculator {

    public static void main(String[] args) {
        String imagePath = "E:\\工作\\其他\\水土保持管家\\新建文本文档.txt";
        StringBuilder stringBuilder = new StringBuilder();
        try (InputStream inputStream = new FileInputStream(imagePath)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                stringBuilder.append(new String(buffer, 0, len));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        String outPath = "E:\\工作\\其他\\水土保持管家\\aaa\\aasd.png";
        // 替换为你的图片路径
        try {
            Base64ToImageConverter.convertBase64ToImage(stringBuilder.toString(), outPath);
            double greenPercentage = calculateGreenPercentage(outPath);
            System.out.println("绿色像素占比: " + greenPercentage + "%");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static double calculateGreenPercentage(String imagePath) throws IOException {
        File file = new File(imagePath);
        BufferedImage image = ImageIO.read(file);

        int width = image.getWidth();
        int height = image.getHeight();
        int greenPixels = 0;
        int totalPixels = width * height;

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int pixel = image.getRGB(x, y);
                int red = (pixel >> 16) & 0xff;
                int green = (pixel >> 8) & 0xff;
                int blue = pixel & 0xff;

                // 判断是否为绿色像素，这里简单地判断绿色通道的值是否大于红色和蓝色通道的值
                if (green > red && green > blue) {
                    greenPixels++;
                }
            }
        }

        return (greenPixels * 100.0) / totalPixels;
    }
}
